package com.wuercloud.http.server;

import com.wuercloud.http.json.codec.HttpJsonRequest;
import com.wuercloud.http.json.codec.HttpJsonResponse;
import com.wuercloud.http.json.pojo.InfoObject;
import com.wuercloud.http.transmit.AsyncInfoTaskService;
import com.wuercloud.utils.FastJsonUtils;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * Created by JiangWL on 2017/2/14.
 */
@Component
@Qualifier("jsonServerHandler")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@ChannelHandler.Sharable
public class HttpJsonServerHandler extends SimpleChannelInboundHandler<HttpJsonRequest> {
    private static Logger log = LoggerFactory.getLogger(HttpJsonServerHandler.class);

    @Autowired
    @Qualifier("httpThreadTaskExecutor")
    private ThreadPoolTaskExecutor httpThreadTaskExecutor;

    @Autowired
    @Qualifier("asyncInfoTaskService")
    private AsyncInfoTaskService asyncInfoTaskService;

    @Override
    protected void channelRead0(final ChannelHandlerContext ctx, HttpJsonRequest msg) throws Exception {
        HttpRequest request = msg.getRequest();

        InfoObject obj = (InfoObject) msg.getBody();
        asyncInfoTaskService.excuteAsyncInfoTask(obj);
        //httpThreadTaskExecutor.submit(new InfoAnalyzer(obj));
        log.info(" HttpServer接收到了ID为"+obj.getId()+"的数据，详细信息内容：" + FastJsonUtils.objectToJson(obj));

        doWriteReturnValue(ctx,obj);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER) //flush掉所有写回的数据
                .addListener(ChannelFutureListener.CLOSE);
    }

    private void doWriteReturnValue(final ChannelHandlerContext ctx,InfoObject obj) {
        obj.setReturnMsg("200");
        log.info(" HttpServer构建了返回对象ID为"+obj.getId()+"的数据。");
        System.out.println("构建内容要素");
        ctx.write(new HttpJsonResponse(null, obj));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            sendError(ctx, INTERNAL_SERVER_ERROR);
        }
    }

    private static void sendError(ChannelHandlerContext ctx,
                                  HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                status, Unpooled.copiedBuffer("失败: " + status.toString()
                + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }
}
